package com.hx.validator;

import cn.hutool.core.util.StrUtil;
import com.hx.cache.CacheDict;
import com.hx.util.SpringUtil;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Set;
import java.util.stream.Collectors;

public class StrContainConstraintValidator implements ConstraintValidator<StrContainValue, String> {
    private Set<String> dict;

    /**
     * 初始化方法
     *
     * @param constraintAnnotation
     */
    @Override
    public void initialize(StrContainValue constraintAnnotation) {
        if (StrUtil.equalsIgnoreCase(constraintAnnotation.matchType().name(), "code")) {
            dict = SpringUtil.getBean(CacheDict.class).getSetDictCodeByKey(constraintAnnotation.key());
        } else if (StrUtil.equalsIgnoreCase(constraintAnnotation.matchType().name(), "name")) {
            dict = SpringUtil.getBean(CacheDict.class).getSetDictNameByKey(constraintAnnotation.key());
        }
    }

    /**
     * 判断是否校验成功
     *
     * @param value   需要校验的值
     * @param context
     * @return
     */
    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (value == null)
            return true;

        String defaultMessage = context.getDefaultConstraintMessageTemplate();
        //禁用默认message值,不禁用会在原有默认的message的基础上进行拼接
        context.disableDefaultConstraintViolation();
        context.buildConstraintViolationWithTemplate(
                StrUtil.format("【{}({})】", defaultMessage, dict.stream().collect(Collectors.joining("/")))
        ).addConstraintViolation();
        return !StrUtil.split(value, "，").stream().anyMatch(str -> !dict.contains(str));
    }
}
